package com.tencent.wxcloudrun.service;

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2023/4/2 13:16
 * @description: TODO
 */
@Service
public class PayService {
    @Value("${wxpay.merchantId}")
    private String merchantId;
    @Value("${wxpay.privateKeyPath}")
    private String privateKeyPath;
    @Value("${wxpay.merchantSerialNumber}")
    private String merchantSerialNumber;
    @Value("${wxpay.apiV3key}")
    private String apiV3key;
    @Value("${wxpay.appid}")
    private String appid;
    public static Config config = null;
    public static NativePayService service = null;
    public PrepayResponse pay(JSONObject jsonObject){
        if (config == null){
            config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(merchantId)
                    .privateKeyFromPath(System.getProperty("user.dir") + privateKeyPath)
                    .merchantSerialNumber(merchantSerialNumber)
                    .apiV3Key(apiV3key)
                    .build();
        }
        if(service==null){
            service = new NativePayService.Builder().config(config).build();
        }
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        Integer money = jsonObject.getInteger("price");
        String orderid = jsonObject.getString("orderid");
        amount.setCurrency("CNY");
        amount.setTotal(money);
        request.setAmount(amount);
        request.setAppid(appid);
        request.setMchid(merchantId);
        request.setDescription(jsonObject.getString("subscriptionid"));
        request.setNotifyUrl("https://pay-33830-5-1302898718.sh.run.tcloudbase.com/pay/callback");
        request.setOutTradeNo(orderid);
        PrepayResponse response = service.prepay(request);
        return response;
    }


}
